package com.yunbao.hujin.myoss;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @anthor zhangchuang QQ:1032006226
 */
public class OkHttpUtils {
    private static Handler mHandler;

    public OkHttpUtils() {
        mHandler = new Handler(Looper.getMainLooper());
    }


    /**
     * 异步请求
     *
     * @param type               方式
     * @param params             参数
     * @param userResultCallback 响应
     */
    public static void asyncRequest(String type, String url, Map<String, String> params, final ResultCallback<String> userResultCallback) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request request = null;
        String mUrl;
        if (type.equals("POST")) {
            String paramsString = "?" + params.toString().substring(1, params.toString().length() - 1).replace(",", "&"); //截取去掉大括号{}
            mUrl = url;

            request = new Request.Builder()
                    .url(mUrl)
                    .build();

        } else if (type.equals("GET")) {
            mUrl =  url;
            FormBody.Builder builder = new FormBody.Builder();

            Iterator<Map.Entry<String, String>> iterator = null;
            if (params != null) {
                iterator = params.entrySet().iterator();
                Map.Entry<String, String> entry;
                while (iterator.hasNext()) {
                    entry = iterator.next();
                    builder.add(entry.getKey(), entry.getValue());
                }
            }
            RequestBody requestBody = builder.build();

            request = new Request.Builder()
                    .url(mUrl)
//                    .header("", "")
//                    .post(requestBody)
                    .build();
        }
        Call call = mOkHttpClient.newCall(request);
        final Request finalRequest = request;

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new OkHttpUtils().sendFailedStringCallback(finalRequest, e, userResultCallback);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    new OkHttpUtils().sendSuccessResultCallback(response.body().string(), userResultCallback);
                } catch (Exception e) {
                    new OkHttpUtils().sendFailedStringCallback(finalRequest, e, userResultCallback);
                }
            }
        });
    }

    /**
     * @author zhangchuang
     * @time 2017/9/19  10:56
     * @describe 同步请求
     */
    public static String syncRequest() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("name", "zc")
                .add("age", "1").build();

        Request request = new Request.Builder()
                .url("http://www.baidu.com")
                .post(requestBody)
                .addHeader("token", "")
                .build();

        final Call call = okHttpClient.newCall(request);
        Response response = call.execute();
        Log.i("tag", "response=" + response.toString());
        return response.body().string();
    }

    private void sendFailedStringCallback(final Request request, final Exception e, final ResultCallback<String> callback) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null)
                    callback.onError(request, e);
            }
        });
    }

    private void sendSuccessResultCallback(final String jsonString, final ResultCallback<String> callback) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onResponse(jsonString);
                }
            }
        });
    }

    public static abstract class ResultCallback<T> {

        public abstract void onError(Request request, Exception e);

        public abstract void onResponse(T response);
    }
}
